package academic.ui.server;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.torque.NoRowsException;
import org.apache.torque.TooManyRowsException;
import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;

import torque.generated.CustomersPeer;

import com.oreilly.servlet.MultipartRequest;

import ecommerce.soco.server.util.ImgUtil;
import ecommerce.soco.server.util.SocoCopierBase;


public class FileUpload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2873757852660151599L;

	
	
	
	public FileUpload() {
		super();
		// Create a factory for disk-based file items
		
	}
		
	@Override
	  public final void doPost(HttpServletRequest request,
	      HttpServletResponse response) {
		
		MultipartRequest req;
		try {
		req = new MultipartRequest(request,System.getProperty("homeDir")+"/TEMP");
		File f=req.getFile("upload");
		String customerID = req.getParameter("customerID");
		String directoryPath = System.getProperty("homeDir")+"/Files/Users/"+customerID+"/";
		
		FileUtils.deleteDirectory(new File(directoryPath));
		FileUtils.forceMkdir(new File(directoryPath));
		File destFile = new File(directoryPath);
		Double imgRatio = ImgUtil.getImageRatio(f.getPath());
		CustomersPeer.doUpdate(new Criteria().add(CustomersPeer.CUSTOMERS_ID, Integer.parseInt(customerID)),
				new Criteria().add(CustomersPeer.CUSTOMERS_PHOTO,f.getName()).add(CustomersPeer.PHOTO_RATIO,SocoCopierBase.getBigDecimalFromDouble(imgRatio) ));
			FileUtils.copyFileToDirectory( f, destFile );
		
		response.setContentType("text/html");
		response.getWriter().printf("{ \"filename\": \"%s\",\"ratio\": \"%s\" }", f.getName(),imgRatio);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoRowsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TooManyRowsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TorqueException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		
}
